package quoc.phu;

import InvoikeServices.HeThongInvoike;
import InvoikeServices.Protocol;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.gcm.GCMRegistrar;

public class DangNhapActivity extends Activity {
	Button btnDangNhap;
	TextView txtTenDangNhap, txtMatKhau, txtLoi;
	ProgressDialog mProgressDialog;
	AsyncTask<String, Void, Boolean> mDangNhapTask;
	String regId = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dang_nhap);
		btnDangNhap = (Button) findViewById(R.id.btnDangNhap);
		txtMatKhau = (TextView) findViewById(R.id.txtMatKhau);
		txtTenDangNhap = (TextView) findViewById(R.id.txtTenDanNhap);
		txtLoi = (TextView) findViewById(R.id.txtLoi);
		txtTenDangNhap.setText("phu");
		txtMatKhau.setText("phu");
		initProgressDialog();
		regId = GCMRegistrar.getRegistrationId(this);
		HeThongInvoike.register(this);
		if (regId == "") {
			GCMRegistrar.register(this, Protocol.SENDER_ID);

		}
		regId = GCMRegistrar.getRegistrationId(this);
		btnDangNhap.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				initDangNhapTask();
				mDangNhapTask.execute(txtTenDangNhap.getText().toString(), txtMatKhau.getText().toString(), regId);

			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_dang_nhap, menu);
		return true;
	}

	private void initDangNhapTask() {
		mDangNhapTask = new AsyncTask<String, Void, Boolean>() {

			@Override
			protected Boolean doInBackground(String... params) {
				try {
					return HeThongInvoike.DangNhap(params[0], params[1], params[2]);
				} catch (Exception e) {
					return false;
				}
			}

			@Override
			protected void onPostExecute(Boolean result) {
				mProgressDialog.dismiss();
				if (result) {
					Intent iMain=new Intent(getBaseContext(),od_MainActivity.class);
					startActivity(iMain);
				} else {
					txtLoi.setText("Thất bại!");
				}
			}

			@Override
			protected void onPreExecute() {
				mProgressDialog.show();
			}
		};
	}

	private void initProgressDialog() {
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setMessage("Đang kết nối tới máy chủ!");
		mProgressDialog.setButton("Hủy bỏ", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				mDangNhapTask.cancel(true);
			}
		});
	}
}
